package com.sun.lib.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.location.Location;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Looper;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.RequiresApi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * 调用系统
 * author :Created by sk.
 * date : 2016/11/8.
 * email: wangchao@lepu.cn
 */

public class SystemUtil {


    private BufferedReader reader;
    private Process process;

    public static void call400(Context context) {
        callPhone(context, "400-631-2626");
    }

    /**
     * 拨打电话
     *
     * @param context
     * @param tel
     */
    public static void callPhone(Context context, String tel) {
        if (isPad(context))
            return;

        try {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri data = Uri.parse("tel:" + tel);
            intent.setData(data);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断当前设备是手机还是平板，代码来自 Google I/O App for Android
     *
     * @param context
     * @return 平板返回 True，手机返回 False
     */
    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }


    /**
     * 关闭软件盘
     *
     * @param context
     * @param target
     */
    public static void closeSoftware(Context context, View target) {
        if (target != null) {
            InputMethodManager inputmanger = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(target.getWindowToken(), 0);
        }
    }


    /**
     * 关闭软件盘
     *
     * @param aty
     */
    public static void closeSoftware(Activity aty) {
        View target = aty.getWindow().peekDecorView();
        if (target != null) {
            InputMethodManager inputmanger = (InputMethodManager) aty.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(target.getWindowToken(), 0);
        }
    }


    /**
     * 判断view是否完全可见
     *
     * @return
     */
    public static boolean isVisiable(View view) {
        boolean isVisiable = false;
        Rect rect = new Rect();
        isVisiable = view.getGlobalVisibleRect(rect);
        return isVisiable;
    }

    public static boolean isTopActivity(Context context, String TAG) {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(TAG)) {
            isTop = true;
        }
        return isTop;
    }

    public static String getApplicationName(Context context) {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;

        try {
            packageManager = context.getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(context.getApplicationContext().getPackageName(), 0);
        } catch (Exception e) {
            e.printStackTrace();
            applicationInfo = null;
        }

        String applicationName = (String) packageManager.getApplicationLabel(applicationInfo);

        return applicationName;
    }

    /**
     * 判断是否安装了指定包名的应用
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isInstall(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packages = packageManager.getInstalledPackages(0);
        if (packages != null) {
            for (PackageInfo info : packages) {
                if (TextUtils.equals(info.packageName, packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isWeixinAvailable(Context context) {
        return isInstall(context, "com.tencent.mm");
    }

    public static boolean isQQClientAvailable(Context context) {
        return isInstall(context, "com.tencent.mobileqq");
    }

    /**
     * 进入到引用设置权限界面
     *
     * @param context
     */
    public static void settingPermisssion(Context context) {
        Intent intent = null;
        if (Build.VERSION.SDK_INT >= 9) {
            Uri packageURI = Uri.parse("package:" + context.getPackageName());
            intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
            context.startActivity(intent);
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            context.startActivity(intent);
        }
    }

    public static int getWindowWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        return windowManager.getDefaultDisplay().getWidth();
    }


    public static boolean isNetWorkConnected(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            @SuppressLint("MissingPermission") NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String toDBC(String input) {
        if (TextUtils.isEmpty(input)) return input;
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }


    /**
     * 判断是否开启通知
     *
     * @param context
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {
        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static Map<String, String> getWifiNetInfo(Context context) {
        Map<String, String> wifiInfo = new HashMap<>();
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiInfo != null) {
            DhcpInfo info = wifiManager.getDhcpInfo();
            wifiInfo.put("wifi-dns", intToIp(info.dns1) + ";" + intToIp(info.dns2));
            wifiInfo.put("wifi-gateway", intToIp(info.gateway));
            wifiInfo.put("wifi-ip", intToIp(info.ipAddress));
            wifiInfo.put("wifi-netmask", intToIp(info.netmask));
            wifiInfo.put("wifi-leaseTime", String.valueOf(info.leaseDuration));
            wifiInfo.put("wifi-dhcpServer", intToIp(info.serverAddress));
        }
        return wifiInfo;
    }

    public static String intToIp(int addr) {
        return ((addr & 0xFF) + "." +
                ((addr >>>= 8) & 0xFF) + "." +
                ((addr >>>= 8) & 0xFF) + "." +
                ((addr >>>= 8) & 0xFF));
    }

    /**
     * 获取dns
     *
     * @return
     */
    public String getLocalDNS() {
        String dnsIP = "";
        try {
            process = Runtime.getRuntime().exec("getprop net.dns1");
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            dnsIP = reader.readLine();
            return dnsIP;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                process.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return dnsIP;
    }

    /**
     * 获取图片的经纬度
     *
     * @param path
     * @return
     */
    public static Location getImageLoc(String path) {
        Location location = new Location("exif");
        if (TextUtils.isEmpty(path)) {
            return location;
        }
        try {
            ExifInterface exif = new ExifInterface(path);
            String sLat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
            String sLon = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
            String latR = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
            String lonR = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);

            double lat = dms2Dbl(sLat);
            if (lat > 180.0) return location;
            double lon = dms2Dbl(sLon);
            if (lon > 180.0) return location;

            lat = latR.contains("S") ? -lat : lat;
            lon = lonR.contains("W") ? -lon : lon;

            location.setLatitude(lat);
            location.setLongitude(lon);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return location;

    }

    private static double dms2Dbl(String DMS) {
        double dRV = 999.0;
        try {
            String[] DMSs = DMS.split(",", 3);
            String s[] = DMSs[0].split("/", 2);
            dRV = (new Double(s[0]) / new Double(s[1]));

            s = DMSs[1].split("/", 2);
            dRV += ((new Double(s[0]) / new Double(s[1])) / 60);
            s = DMSs[2].split("/", 2);
            dRV += ((new Double(s[0]) / new Double(s[1])) / 3600);
        } catch (Exception e) {
        }
        return dRV;
    }

    public static void setImageLoc(String path, String oldPath) {
        if (TextUtils.isEmpty(path) || TextUtils.isEmpty(oldPath)) return;
        if (TextUtils.equals(path, oldPath)) return;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            ExifInterface oldExif = new ExifInterface(oldPath);
            exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, oldExif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
            exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE, oldExif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
            exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, oldExif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF));
            exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, oldExif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF));
            exifInterface.saveAttributes();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }


}
